package org.xiji.iterator;

import java.util.ArrayList;
import java.util.List;

/**
 * 定义自己的 列表迭代器
 */
public class MyList<T> implements Iterator<T> {
    /***
     * 定义遍历元素集合
     */
    private List<T> list = new ArrayList<T>();

    /**
     *
     * 定义起始变量
     */
    private int index=0;
    @Override
    public boolean hasNext() {


        if (this.index < list.size() || this.index<=0) {
            return true;
        }
        this.index = 0;//指针归零
        return false;
    }

    @Override
    public T next() {
        //如果遍历的元素不为零继续遍历
        if(!hasNext()){
            throw new RuntimeException("指针异常");
        }
        return list.get(this.index++);
    }

    @Override
    public void add(T t) {
        this.list.add(t);
    }

    @Override
    public void remove() {
        if (this.list.size() <= 0) {

            throw new RuntimeException("指针超出范围");
        }
        //移除最后一个元素
        this.list.remove(this.list.size() - 1);
        //指针起始指针变为零

    }

    @Override
    public void remove(int index) {
        if (index < 0 || index >= this.list.size()) {
            throw new RuntimeException("指针超出范围");
        }
        this.list.remove(index);

    }
    

}
